package com.tmt.im.common.yunxin.impls;

import com.alibaba.fastjson2.JSONObject;
import com.tmt.im.common.Constant;
import com.tmt.im.common.yunxin.ErrorCode;
import com.tmt.im.common.yunxin.IYunXinConfig;
import com.tmt.im.common.yunxin.IYunXinMsgSender;
import com.tmt.im.common.yunxin.YunXinHelper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/28 10:55
 * @Version 1.0
 **/
@Order(1)
public class DefaultYunXinMsgSender_V10 implements IYunXinMsgSender, ApplicationContextAware {

    private static final String SEND_SYSTEM_NOTIFY_URL = "https://open.yunxinapi.com/im/v2/custom_notification";

    private static final String BATCH_SEND_SYSTEM_NOTIFY_URL = " https://open.yunxinapi.com/im/v2/custom_notification/batch";

    private IYunXinConfig yunXinConfig;

    @Override
    public boolean sendCustomizedMsg(Long from, Long to, JSONObject content, StringBuilder error) {
        return false;
    }

    @Override
    public boolean sendMsg(Long senderId, Long receiverId, int msgType, JSONObject msg, StringBuilder error) {
        try {
            MultiValueMap<String, Object> reqParam = new LinkedMultiValueMap<>();
            reqParam.add("sender_id", "" + senderId);
            reqParam.add("type", msgType);
            reqParam.add("receiver_id", "" + receiverId);
            reqParam.add("content", msg.toJSONString());

            JSONObject jsonObject = YunXinHelper.exchange(SEND_SYSTEM_NOTIFY_URL, HttpMethod.POST, reqParam, yunXinConfig);
            Long code = jsonObject.getLong("code");
            if (code == 200L) {
                return true;
            }
            throwExceptionByCode(code, jsonObject);
        } catch (Exception ex) {
            error.append(ex.getMessage());
        }
        return false;
    }

    @Override
    public boolean sendMsgInSession(Long senderId, Long tid, List<Long> receiverIds, int msgType, JSONObject msg, StringBuilder error) {
        try {
            MultiValueMap<String, Object> reqParam = new LinkedMultiValueMap<>();
            reqParam.add("sender_id", "" + senderId);
            reqParam.add("receiver_ids", receiverIds.stream().map(x -> "" + x).collect(Collectors.toList()));
            reqParam.add("content", msg.toJSONString());

            JSONObject jsonObject = YunXinHelper.exchange(BATCH_SEND_SYSTEM_NOTIFY_URL, HttpMethod.POST, reqParam, yunXinConfig);
            Long code = jsonObject.getLong("code");
            if (code == 200L) {
                return true;
            }
            throwExceptionByCode(code, jsonObject);
        } catch (Exception ex) {
            error.append(ex.getMessage());
        }
        return false;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        yunXinConfig = applicationContext.getBean(IYunXinConfig.class);
    }

    private void throwExceptionByCode(Long code, JSONObject jsonObject) throws Exception {
        String errorInfo = ErrorCode.getErrorMessage(Constant.YUN_XIN_API_VERSION, code);
        if (StringUtils.hasText(errorInfo)) {
            if (code == 414L) {
                errorInfo = MessageFormat.format(errorInfo, jsonObject.get("msg"));
            }
            throw new Exception(errorInfo);
        } else {
            throw new Exception(MessageFormat.format("云信业务错误:{0}", "" + code));
        }
    }

}
